package com.csi.controller.user;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson2.JSON;
import com.csi.domain.History;
import com.csi.domain.User;
import com.csi.pojo.Result;
import com.csi.service.HistoryService;
import com.csi.service.UserService;
import com.csi.service.impl.HistoryServiceImpl;
import com.csi.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/user/checkPayPasswordAfterController")
public class CheckPayPasswordAfterController extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        UserService userService = new UserServiceImpl();

        // 获取请求参数
        String userNumber = req.getParameter("userNumber");
        String accountNumber = req.getParameter("accountNumber");
        String targetUserNumber = req.getParameter("targetUserNumber");
        String payType = req.getParameter("payType");
        double amount = Double.parseDouble(req.getParameter("amount"));

        // 参数校验
        if (StringUtils.isEmpty(userNumber) || StringUtils.isEmpty(payType)) {
            Result result = new Result<>();
            result.setCode(400);
            result.setMsg("请求参数不能为空");
            out.print(JSON.toJSONString(result));
            out.flush();
            out.close();
            return;
        }


        if (targetUserNumber.length() != 12) {
            Result result = new Result<>();
            result.setCode(400);
            result.setMsg("格式不正确");
            out.print(JSON.toJSONString(result));
            return;
        }

        // 遍历所有用户，查看是否存在该targetUserNumber
        boolean targetUserExists = false;
        for (User user : userService.findAll()) {
            if (targetUserNumber.equals(user.getUserNumber())) {
                targetUserExists = true;
                break;
            }
        }
        if (!targetUserExists) {
            Result result = new Result<>();
            result.setCode(400);
            result.setMsg("对方账户不存在");
            out.print(JSON.toJSONString(result));
            return;
        }

        try {

            // 判断支付方式并进行支付
            if ("钱包".equals(payType)) {

                // 钱包支付
                HistoryService historyService = new HistoryServiceImpl();

                // 判断钱包余额
                double balance = userService.queryBalance(userNumber);
                if (balance < amount) {
                    Result result = new Result<>();
                    result.setCode(7000);
                    result.setMsg("钱包余额不足");
                    out.print(JSON.toJSONString(result));
                    return;
                }

                // 判断有没有超过每日限额
                double payLimit = userService.queryPayLimit(userNumber);
                if (amount > payLimit) {
                    Result result = new Result<>();
                    result.setCode(7001);
                    result.setMsg("超过钱包每日限额");
                    out.print(JSON.toJSONString(result));
                    return;
                }

                // 判断现在要支付的金额加上今日历史的金额是否超过限额
                Double todayAmount = historyService.queryTodayAmount(userNumber);
                if (todayAmount + amount > payLimit) {
                    Result result = new Result<>();
                    result.setCode(7002);
                    result.setMsg("超过今日限额");
                    out.print(JSON.toJSONString(result));
                    return;
                }

                //支付
                userService.payByWallet(userNumber,targetUserNumber,amount);

                // 记录支付历史
                History history = new History();
                history.setUserNumber(userNumber);
                history.setOperationType("支付");
                history.setPayOut(userNumber);
                history.setPayIn(targetUserNumber);
                history.setAmount(amount);
                historyService.add(history);

                Result result = new Result<>();
                result.setCode(200);
                result.setMsg("支付成功");
                out.print(JSON.toJSONString(result));
            } else if ("储蓄卡/活期账户".equals(payType)) {

                // 普通银行卡支付
                HistoryService historyService = new HistoryServiceImpl();

				// 查询用户账户（储蓄卡、活期账户）可用余额
                double availableBalance = userService.queryAvailableBalance(userNumber);

				// 判断账户余额是否足够支付
                if (availableBalance < amount) {
                    Result result = new Result<>();
                    result.setCode(7000);
                    result.setMsg("账户余额不足");
                    out.print(JSON.toJSONString(result));
                    return;
                }

				// 判断有没有超过每日限额
                double payLimit = userService.queryPayLimit(userNumber);
                if (amount > payLimit) {
                    Result result = new Result<>();
                    result.setCode(7001);
                    result.setMsg("超过每日限额");
                    out.print(JSON.toJSONString(result));
                    return;
                }

				// 判断现在要支付的金额加上今日历史的金额是否超过限额
                Double todayAmount = historyService.queryTodayAmount(userNumber);
                if (todayAmount + amount > payLimit) {
                    Result result = new Result<>();
                    result.setCode(7002);
                    result.setMsg("超过今日限额");
                    out.print(JSON.toJSONString(result));
                    return;
                }

				// 支付
                userService.payByAccount(accountNumber, targetUserNumber, amount);

				// 记录支付历史
                History history = new History();
                history.setUserNumber(userNumber);
                history.setOperationType("支付");
                history.setPayOut(userNumber);
                history.setPayIn(targetUserNumber);
                history.setAmount(amount);
                historyService.add(history);

                Result result = new Result<>();
                result.setCode(200);
                result.setMsg("支付成功");
                out.print(JSON.toJSONString(result));


            } else if ("信用卡".equals(payType)) {

                // 信用卡支付
                HistoryService historyService = new HistoryServiceImpl();

				// 查询用户信用卡可用额度
                double availableLimit = userService.queryAvailableLimit(userNumber);

				// 判断信用卡可用额度是否足够支付
                if (availableLimit < amount) {
                    Result result = new Result<>();
                    result.setCode(7000);
                    result.setMsg("信用卡可用额度不足");
                    out.print(JSON.toJSONString(result));
                    return;
                }

				// 判断有没有超过每日限额
                double payLimit = userService.queryPayLimit(userNumber);
                if (amount > payLimit) {
                    Result result = new Result<>();
                    result.setCode(7001);
                    result.setMsg("超过每日限额");
                    out.print(JSON.toJSONString(result));
                    return;
                }

				// 判断现在要支付的金额加上今日历史的金额是否超过限额
                Double todayAmount = historyService.queryTodayAmount(userNumber);
                if (todayAmount + amount > payLimit) {
                    Result result = new Result<>();
                    result.setCode(7002);
                    result.setMsg("超过今日限额");
                    out.print(JSON.toJSONString(result));
                    return;
                }

				// 支付
                userService.payByCredAccount(accountNumber, targetUserNumber, amount);

				// 记录支付历史
                History history = new History();
                history.setUserNumber(userNumber);
                history.setOperationType("支付");
                history.setPayOut(userNumber);
                history.setPayIn(targetUserNumber);
                history.setAmount(amount);
                historyService.add(history);

                Result result = new Result<>();
                result.setCode(200);
                result.setMsg("支付成功");
                out.print(JSON.toJSONString(result));

            }

        } catch (Exception e) {
            Result result = new Result<>();
            result.setCode(500);
            result.setMsg("服务器内部错误");
            out.print(JSON.toJSONString(result));
            e.printStackTrace();
        } finally {
            out.flush();
            out.close();
        }
	}
}
